package com.tjing.bussiness.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import com.tjing.bussiness.model.QhWxUser;
import com.tjing.frame.controller.ToolController;
import com.tjing.frame.object.ClassInfo;
import com.tjing.frame.object.RequestObject;
import com.tjing.frame.services.DbServices;
import com.tjing.frame.util.CodeHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import pojo.OAuthInfo;
import pojo.UserInfo;
import util.WeixinUtil;
import util.Constants;

/**
 * Created by cwp on 2017/2/8.
 */
@Controller
@RequestMapping("/interface")
public class InterfaceController {
    @Autowired
    private RestTemplate rt;
    @Autowired
    private DbServices dbServices;

    private String postUrl="http://wx.54pai.cn:36020/api/commonEntry/callFun/";
    @RequestMapping("/getCaptchaCode")
    public String getCaptchaCode(HttpServletRequest request) {
        return rt.postForObject(postUrl + "getCaptchaCode", null, String.class);
    }

    @RequestMapping("/teacherLogin")
    public void teacherLogin(HttpServletRequest request,HttpServletResponse response) throws Exception{
        JSONObject param = CodeHelper.getRequestParams(request);
        String uid=param.getString("uid");
        String pwd=param.getString("pwd");
        String USR_TYPE="1";
        String clientType="2";
        String resultStr = rt.postForObject(postUrl + "teacherLogin?uid={uid}&pwd={pwd}&USR_TYPE={USR_TYPE}&clientType={clientType}", null, String.class,uid,pwd,USR_TYPE,clientType);

        response.setCharacterEncoding("utf-8");
        PrintWriter writer =  response.getWriter();
        writer.print(resultStr.toString());
        writer.close();
    }

    @RequestMapping(value="/loadFormData")
    public ResponseEntity<JSONObject> loadFormData(RequestObject requestObject) throws ClassNotFoundException {
        ClassInfo classInfo = CodeHelper.getClassInfo(requestObject.getPoName());
        Class<?> clazzObj = Class.forName(classInfo.getFullName());
        JSONObject jobj = null;
        if(StringUtils.isEmpty(requestObject.getId())){
            jobj = new JSONObject();
        }else{
            Object entity = dbServices.getEntity(clazzObj, Integer.valueOf(requestObject.getId()));
            jobj = JSON.parseObject(JSON.toJSONString(entity));
        }
        ResponseEntity<JSONObject> responseEntity = new ResponseEntity<JSONObject>(jobj, HttpStatus.OK);
        return responseEntity;
    }

    @RequestMapping("/oauth")
    public String oauth(HttpServletRequest request) {
        JSONObject param = CodeHelper.getRequestParams(request);
        String code=param.getString("code");
        if(null != code && !"".equals(code)){
            OAuthInfo oa=null;
            UserInfo info=null;
            try {
                oa = WeixinUtil.getOAuthOpenId(Constants.appId,
                        Constants.appSecret, code);
                info = WeixinUtil.getUserInfo(oa.getAccessToken(),
                        oa.getOpenId());
            } catch (Exception e) {
                return "";
            }
            if(!"".equals(oa) && null != oa){
                String ranCode="";
                int i = 0;
                HashMap<Integer, Object> intParamMap = new HashMap();
                intParamMap.put(i++, oa.getOpenId());
                String hql = "from QhWxUser where openid=?";
                List<QhWxUser> qhWxUsers = dbServices.findListByHql(hql, intParamMap);
                if(qhWxUsers.size()==0){
                    ranCode=ToolController.GetRandNum(6);
                    List<JSONObject> jsonObjects = Lists.newArrayList();
                    JSONObject jobj = new JSONObject();
                    jobj.put("ranCode", ranCode);
                    jobj.put("openId", oa.getOpenId());
                    jobj.put("nickName",info.getNickname());
                    jobj.put("sex", info.getSex());
                    jobj.put("province", info.getProvince());
                    jobj.put("city", info.getCity());
                    jobj.put("country", info.getCountry());
                    jobj.put("headImgUrl", info.getHeadimgurl());
                    jobj.put("createUser", oa.getOpenId());
                    jobj.put("createDateTime", new Date());
                    jobj.put("modifyUser", oa.getOpenId());
                    jobj.put("modifyDateTime", new Date());
                    jobj.put("state", 99);

                    jsonObjects.add(jobj);

                    dbServices.saveOrupdateRecords("QhWxUser", jsonObjects, null,false);
                }
                else{
                    ranCode=qhWxUsers.get(0).getRanCode();
                }

                HttpSession session = request.getSession();
                session.setAttribute("ranCode", ranCode);

                return "app/wechat";

            }else{
                return "";
            }
        }else{
            return "";
        }
    }

}
